package des;

import java.util.Properties;
import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

public class CopyJarUtil {

    //复制jar by jarFile
    public void copyJarByJarFile(File src, File des, String file, Properties pro) throws IOException {
        //重点
        JarFile jarFile = new JarFile(src);
        Enumeration<JarEntry> jarEntrys = jarFile.entries();
        JarOutputStream jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(des)));
        byte[] bytes = new byte[1024];

        while (jarEntrys.hasMoreElements()) {
            JarEntry entryTemp = jarEntrys.nextElement();
            if (entryTemp.getName().equals(file)) {
                jarOut.putNextEntry(new JarEntry(file));
                jarOut.write(readFile(pro).getBytes());
            } else {
                jarOut.putNextEntry(entryTemp);
                BufferedInputStream in = new BufferedInputStream(jarFile.getInputStream(entryTemp));
                int len = in.read(bytes, 0, bytes.length);
                while (len != -1) {
                    jarOut.write(bytes, 0, len);
                    len = in.read(bytes, 0, bytes.length);
                }
                in.close();
            }

            jarOut.closeEntry();
            System.out.println("Copyed: " + entryTemp.getName());
        }

        jarOut.finish();
        jarOut.close();
        jarFile.close();
    }

    private String readFile(Properties prop) {
        StringBuffer buf = new StringBuffer();
        Enumeration<?> enu = prop.propertyNames();
        while (enu.hasMoreElements()) {
            Object key = enu.nextElement();
            System.out.println(key);
            buf.append(key+"="+prop.getProperty((String) key));
            buf.append(System.getProperty("line.separator"));
        }
        return buf.toString();
    }

    public static void main(String[] args) {
        CopyJarUtil d = new CopyJarUtil();
        Properties prop = new Properties();
        prop.setProperty("EncryptKey", "EncryptKey");
        prop.setProperty("c","c0");
        prop.setProperty("protectedPwd", "3");
        prop.setProperty("initPassword", "initPassword3456789");
        try {
            d.copyJarByJarFile(new File("D:\\D\\file\\hik\\clientx11.jar"),
                    new File("D:\\D\\file\\hik\\clientx14.jar")
                    ,"application.properties",prop);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
